package com.dj.ms.configure;

import io.micrometer.core.instrument.MeterRegistry;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Counter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;


/**
 * <br>
 * <p>
 * - prometheus cfg
 * </p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/11/10 上午9:33
 */
@Slf4j
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE - 10)
public class PrometheusConfiguration {

    private CollectorRegistry collectorRegistry = CollectorRegistry.defaultRegistry;

    @Bean("requestTotalCountCollector")
    @ConditionalOnMissingBean(Counter.class)
    public Counter requestTotalCountCollector(){
        log.info("Prometheus CountCollector init.");
        return  Counter.build()
                .name("http_requests_total")
                .labelNames("path", "method", "code")
                .help("HTTP请求总量").register(collectorRegistry);
    }

    @Bean
    public MeterRegistryCustomizer<MeterRegistry> configurer(@Value("${spring.application.name}") String applicationName) {
        log.info("Prometheus MeterRegistryCustomizer init.");
        return registry -> registry.config().commonTags("application", applicationName);
    }

}
